<template>
  <div class="from1">
    <van-nav-bar
      title="修改个人信息"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 在vue中可以使用ref属性获取标签 -->
    <!-- <input type="file" ref="avatarfile" style="display:none;" /> -->
    <input
      type="file"
      ref="avatarFile"
      style="display: none;"
      @change="selectedFile"
    />
    <img :src="avatar | dalImg" alt="头像" @click="selImg" />
    <van-form validate-first>
      <van-field name="pattern" placeholder="请输入昵称" v-model="nickName" />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" @click="save"
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import axios from "axios";
import { uploadUrl } from "../utils/tools";
import { loadUserInfoAPI, modifyInfo } from "../services/users";

export default {
  name: "UserInfo",
  data() {
    return {
      // user: {},
      nickName: "",
      avatar: "",
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    async loadData() {
      const res = await loadUserInfoAPI();
      // this.user = res.data;
      this.nickName = res.data.nickName;
      this.avatar = res.data.avatar;
    },
    async save() {
      if (this.nickName) {
        await modifyInfo({ nickName: this.nickName, avatar: this.avatar });
        this.$router.push({
          name: "User",
        });
      }
    },
    onClickLeft() {
      this.$router.push({
        name: "User",
      });
    },
    selImg() {
      //regs可以获取当前组件中设置了ref属性的标签
      console.log(this.$refs);
      console.log(this.$refs.avatarFile);
      this.$refs.avatarFile.click();
    },
    selectedFile() {
      console.log(this.$refs.avatarFile.files);
      const formData = new FormData();
      formData.append("file", this.$refs.avatarFile.files[0]);
      axios.post(uploadUrl, formData).then((res) => {
        this.avatar = res.data.data;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.from {
  // margin-top: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.from1 img {
  display: block;
  margin: 0 auto;
  top: 40px;
  width: 30vw;
  // height: 40vh;
  border-radius: 50%;
}
</style>
